/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 ~ 2010 Patrick Huy <patrick.huy@frz.cc> 
                       Matthias Butz <matze@odinms.de>
                       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License version 3
    as published by the Free Software Foundation. You may not use, modify
    or distribute this program under any other version of the
    GNU Affero General Public License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package client.messages.commands;

import java.rmi.RemoteException;

import client.IItem;
import client.GameConstants;
import client.ISkill;
import client.Item;
import client.Equip;
import client.MapleClient;
import client.MapleInventoryType;
import client.MapleStat;
import client.SkillFactory;
import client.messages.Command;
import client.messages.CommandDefinition;
import client.messages.IllegalCommandSyntaxException;
import static client.messages.CommandProcessor.getOptionalIntArg;
import handling.channel.ChannelServer;
import handling.MaplePacket;
import java.util.Map;
import java.util.Map.Entry;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MapleShopFactory;
import server.life.MapleMonster;
import server.maps.MapleMapObject;
import tools.ArrayMap;
import tools.packet.MobPacket;
import tools.MaplePacketCreator;
import tools.Pair;
import tools.StringUtil;

public class CharCommands implements Command {

    @Override
    public void execute(MapleClient c, String[] splitted) throws Exception, IllegalCommandSyntaxException {

	if (splitted[0].equals("!lowhp")) {
	    c.getPlayer().getStat().setHp(1);
	    c.getPlayer().getStat().setMp(500);
	    c.getPlayer().updateSingleStat(MapleStat.HP, 1);
	    c.getPlayer().updateSingleStat(MapleStat.MP, 500);

	} else if (splitted[0].equals("!fullhp")) {
	    c.getPlayer().getStat().setHp(c.getPlayer().getStat().getMaxHp());
	    c.getPlayer().getStat().setMp(c.getPlayer().getStat().getMaxMp());
	    c.getPlayer().updateSingleStat(MapleStat.HP, c.getPlayer().getStat().getMaxHp());
	    c.getPlayer().updateSingleStat(MapleStat.MP, c.getPlayer().getStat().getMaxMp());


} else if (splitted[0].equals("!clearinv")) {
		Map<Pair<Short, Short>, MapleInventoryType> eqs = new ArrayMap<Pair<Short, Short>, MapleInventoryType>();
		if (splitted[1].equals("all")) {
	    		for (MapleInventoryType type : MapleInventoryType.values()) {
	    			for (IItem item : c.getPlayer().getInventory(type)) {
					eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), type);
				}
			}
		} else if (splitted[1].equals("eqp")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.EQUIPPED)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.EQUIPPED);
			}
		} else if (splitted[1].equals("eq")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.EQUIP)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.EQUIP);
			}
		} else if (splitted[1].equals("u")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.USE)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.USE);
			}
		} else if (splitted[1].equals("s")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.SETUP)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.SETUP);
			}
		} else if (splitted[1].equals("e")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.ETC)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.ETC);
			}
		} else if (splitted[1].equals("c")) {
	    		for (IItem item : c.getPlayer().getInventory(MapleInventoryType.CASH)) {
				eqs.put(new Pair<Short, Short>(item.getPosition(), item.getQuantity()), MapleInventoryType.CASH);
			}
		} else {
			c.getPlayer().dropMessage(6, "[all/eqp/eq/u/s/e/c]");
		}
	for (Entry<Pair<Short, Short>, MapleInventoryType> eq : eqs.entrySet()) {
		MapleInventoryManipulator.removeFromSlot(c, eq.getValue(), eq.getKey().left,  eq.getKey().right, false, false);
	}


		
	} else if (splitted[0].equals("!skill")) {
	    ISkill skill = SkillFactory.getSkill(Integer.parseInt(splitted[1]));
	    byte level = (byte) getOptionalIntArg(splitted, 2, 1);
	    byte masterlevel = (byte) getOptionalIntArg(splitted, 3, 1);

	    if (level > skill.getMaxLevel()) {
		level = skill.getMaxLevel();
	    }
	    c.getPlayer().changeSkillLevel(skill, level, masterlevel);

	} else if (splitted[0].equals("!sp")) {
	    c.getPlayer().setRemainingSp(getOptionalIntArg(splitted, 1, 1));
	    c.getPlayer().updateSingleStat(MapleStat.AVAILABLESP, c.getPlayer().getRemainingSp());

	} else if (splitted[0].equals("!job")) {
	    c.getPlayer().changeJob(Integer.parseInt(splitted[1]));

	} else if (splitted[0].equals("!whereami")) {
	    c.getPlayer().dropMessage(5, "You are on map " + c.getPlayer().getMap().getId());

	} else if (splitted[0].equals("!shop")) {
	    MapleShopFactory shop = MapleShopFactory.getInstance();
	    int shopId = Integer.parseInt(splitted[1]);
	    if (shop.getShop(shopId) != null) {
		shop.getShop(shopId).sendShop(c);
	    }

	} else if (splitted[0].equals("!gainmeso")) {
	    c.getPlayer().gainMeso(Integer.MAX_VALUE - c.getPlayer().getMeso(), true);

	} else if (splitted[0].equals("!levelup")) {
	    if (c.getPlayer().getLevel() < 200) {
		c.getPlayer().gainExp(500000000, true, false, true);
	    }

	    /*	} else if (splitted[0].equals("!unlockinv")) {
	    for (MapleInventoryType type : MapleInventoryType.values()) {
	    for (IItem item : c.getPlayer().getInventory(type)) {
	    byte flag = item.getFlag();

	    if (ItemFlag.LOCK.check(flag)) {
	    item.setFlag((byte) (flag - ItemFlag.LOCK.getValue()));
	    c.getSession().write(MaplePacketCreator.updateSpecialItemUse(item, type.getType()));
	    }
	    }
	    }*/

	} else if (splitted[0].equals("!item")) {
	    final int itemId = Integer.parseInt(splitted[1]);
	    final short quantity = (short) getOptionalIntArg(splitted, 2, 1);

            if (itemId == 2100106 | itemId == 2100107){
                c.getPlayer().dropMessage(5, "Item is blocked.");
                return;
            }
	    if (GameConstants.isPet(itemId)) {
		c.getPlayer().dropMessage(5, "Please purshase a pet from the cash shop instead.");
	    } else {
		IItem item;
//		byte flag = 0;
//		flag |= ItemFlag.LOCK.getValue();

		if (GameConstants.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
		    MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
		    item = ii.randomizeStats((Equip) ii.getEquipById(itemId));
//		    item.setFlag(flag);
		} else {
		    item = new Item(itemId, (byte) 0, (short) quantity, (byte) 0);
//		    item.setFlag(flag);
		}
		item.setOwner(c.getPlayer().getName());
		item.setGMLog(c.getPlayer().getName());

		MapleInventoryManipulator.addbyItem(c, item);
	    }
	} else if (splitted[0].equals("!drop")) {
	    final int itemId = Integer.parseInt(splitted[1]);
	    final short quantity = (short) (short) getOptionalIntArg(splitted, 2, 1);


                        if (itemId == 2100106 | itemId == 2100107){
                c.getPlayer().dropMessage(5, "Item is blocked.");
                return;
                        }
	    if (GameConstants.isPet(itemId)) {
		c.getPlayer().dropMessage(5, "Please purshase a pet from the cash shop instead.");
	    } else {
		IItem toDrop;
		if (GameConstants.getInventoryType(itemId) == MapleInventoryType.EQUIP) {
		    MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
		    toDrop = ii.randomizeStats((Equip) ii.getEquipById(itemId));
		} else {
		    toDrop = new Item(itemId, (byte) 0, (short) quantity, (byte) 0);
		}
		toDrop.setGMLog(c.getPlayer().getName());

		c.getPlayer().getMap().spawnItemDrop(c.getPlayer(), c.getPlayer(), toDrop, c.getPlayer().getPosition(), true, true);
	    }

	} else if (splitted[0].equals("!level")) {
	    c.getPlayer().setLevel(Short.parseShort(splitted[1]));
	    c.getPlayer().levelUp();
	    if (c.getPlayer().getExp() < 0) {
		c.getPlayer().gainExp(-c.getPlayer().getExp(), false, false, true);
	    }

	} else if (splitted[0].equals("!online")) {
	    c.getPlayer().dropMessage(6, "Characters connected to channel " + c.getChannel() + ":");
	    c.getPlayer().dropMessage(6, c.getChannelServer().getPlayerStorage().getOnlinePlayers(true));

	} else if (splitted[0].equals("!say")) {
	    if (splitted.length > 1) {
		StringBuilder sb = new StringBuilder();
		sb.append("[");
		sb.append(c.getPlayer().getName());
		sb.append("] ");
		sb.append(StringUtil.joinStringFrom(splitted, 1));
		MaplePacket packet = MaplePacketCreator.serverNotice(6, sb.toString());
		try {
		    ChannelServer.getInstance(c.getChannel()).getWorldInterface().broadcastMessage(packet.getBytes());
		} catch (RemoteException e) {
		    c.getChannelServer().reconnectWorld();
		}
	    } else {
		c.getPlayer().dropMessage(6, "Syntax: !say <message>");
	    }
  //          } else if (splitted[0].equalsIgnoreCase("!maxskills")) {
//            getplayer.maxAllSkills();
	} else if (splitted[0].equals("!vac")) {
	    if (!c.getPlayer().isHidden()) {
		c.getPlayer().dropMessage(6, "You can only vac monsters while in hide.");
	    } else {
		for (final MapleMapObject mmo : c.getPlayer().getMap().getAllMonster()) {
		    final MapleMonster monster = (MapleMonster) mmo;
		    c.getPlayer().getMap().broadcastMessage(MobPacket.moveMonster(false, -1, 0, 0, 0, 0, monster.getObjectId(), monster.getPosition(), c.getPlayer().getLastRes()));
		    monster.setPosition(c.getPlayer().getPosition());
		}
	    }
	} else if (splitted[0].equals("!song")) {
	    c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.musicChange(splitted[1]));
	} else if (splitted[0].equals("!mutecall")) {
		c.getPlayer().setCallGM(!c.getPlayer().isCallGM());
		c.getPlayer().dropMessage(6, "GM Messages set to " + c.getPlayer().isCallGM());
	}
    }

    @Override
    public CommandDefinition[] getDefinition() {
	return new CommandDefinition[]{
		    new CommandDefinition("song", "", "", 2),
		    new CommandDefinition("lowhp", "", "", 2),
		    new CommandDefinition("fullhp", "", "", 2),
		    new CommandDefinition("skill", "", "", 2),
		    new CommandDefinition("sp", "", "", 2),
		    new CommandDefinition("job", "", "", 2),
		    new CommandDefinition("whereami", "", "", 2),
		    new CommandDefinition("shop", "", "", 2),
		    new CommandDefinition("gainmeso", "", "", 5), // Meso are untraceable, which may fk up the economy if the GM tries to screw us.
		    new CommandDefinition("levelup", "", "", 2),
		    new CommandDefinition("item", "", "", 4),
		    new CommandDefinition("drop", "", "", 4),
		    new CommandDefinition("level", "", "", 2),
		    new CommandDefinition("online", "", "", 2),
		    new CommandDefinition("mutecall", "", "", 1),
		    new CommandDefinition("clearinv", "all/eqp/eq/u/s/e/c [all/equipped/equip/use/setup/etc/cash]", "Clears all item in the GameMaster's inventory", 3),
                    new CommandDefinition("vac", "", "vacs monster to your position", 2),
		    new CommandDefinition("say", "message", "Talks to the whole world in the format: [Name] message", 2)

        };
    }
}
